import re

from appium.webdriver.common.mobileby import MobileBy
from selenium.common.exceptions import NoSuchElementException

from base.base_page import BasePage
from pages.add_member_page import AddMemberPage
from pages.search_page import SearchPage


class ContactsPage(BasePage):

    _add_member_locator = (MobileBy.XPATH, "//*[@text='添加成员']")
    _search_icon_locator = (
        MobileBy.XPATH, "//android.widget.LinearLayout[count(android.widget.RelativeLayout)=2]/*[1]")
    _members_count_locator = (MobileBy.XPATH, "//*[contains(@text,'未加入')]")

    def go_to_addmember(self):
        self.find_and_click(self._add_member_locator)
        return AddMemberPage(self.driver)

    def go_to_search_page(self):
        self.find_and_click(self._search_icon_locator)
        return SearchPage(self.driver)

    def get_member_count(self):
        try:
            tmp_str = self.find(self._members_count_locator).text
            member_count = int(re.search(r"\d+", tmp_str).group(0))
        except NoSuchElementException:
            # 只有创建人的时候，通讯录页面不会显示人数
            member_count = 1
        return member_count


